package main

import (
	// "encoding/json"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/gogap/ali_mns"
	"github.com/gogap/logs"
	//"io/ioutil"
	//"time"
	"log"
	"net/http"
)

type appConf struct {
	Url             string `json:"url"`
	Queue           string `json:"queue"`
	AccessKeyId     string `json:"access_key_id"`
	AccessKeySecret string `json:"access_key_secret"`
	Delete          bool   `json:"delete"`
}

type response struct {
	Topic string `json:"topic"`
}

var topic = "null"

func main() {
	go g()

	http.HandleFunc("/r", handler)
	http.HandleFunc("/d", del)
	http.Handle("/", http.FileServer(http.Dir("static")))
	log.Fatal(http.ListenAndServe(":1323", nil))

	fmt.Println("http server listening")

}

func base64Encode(str string) string {
	return base64.StdEncoding.EncodeToString([]byte(str))
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, topic)
}

func del(w http.ResponseWriter, r *http.Request) {
	topic = "null"
	fmt.Fprintf(w, "success")
}

func g() {
	conf := appConf{
		Url:             "https://1622570428194245.mns.cn-shanghai.aliyuncs.com/",
		Queue:           "aliyun-iot-a1l7anRRgND",
		AccessKeyId:     "LTAIFtWDdjrtzcFm",
		AccessKeySecret: "SFvW8bWKFn00TdwMvw3B8GVnSPF23z",
		Delete:          true,
	}

	client := ali_mns.NewAliMNSClient(conf.Url,
		conf.AccessKeyId,
		conf.AccessKeySecret)

	queue := ali_mns.NewMNSQueue(conf.Queue, client)

	respChan := make(chan ali_mns.MessageReceiveResponse)
	errChan := make(chan error)
	go func() {
		for {
			select {
			case resp := <-respChan:
				{
					//fmt.Println(string(resp.MessageBody))
					//logs.Pretty("message:", string(resp.MessageBody))
					var ress response
					_ = json.Unmarshal(resp.MessageBody, &ress)
					fmt.Println(string(resp.MessageBody))
					if ress.Topic != "" {
						topic = ress.Topic
					}

					fmt.Println(string(topic))

					if e := queue.DeleteMessage(resp.ReceiptHandle); e != nil {
						logs.Error(e)
					}

				}
			case _ = <-errChan:
				{
					//logs.Error(err)
				}
			}
		}

	}()

	fmt.Println("beginning of the message loop")
	queue.ReceiveMessage(respChan, errChan)
}
